package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2022-04-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
 @Autowired
 private AdminMapper adminMapper;
 @Autowired
 private UserDetailsService userDetailsService;
 @Autowired
 private PasswordEncoder passwordEncoder;
 @Autowired
 private JwtTokenUtils jwtTokenUtils;
 @Value("${jwt.tokenHead}")
 private String tokeHead;
 @Autowired
 private RoleMapper roleMapper;


    @Override
    public Admin getAdminbyUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    @Override
    public RespBean login(String code,String username, String password, HttpServletRequest request) {
        UserDetails userDetails=userDetailsService.loadUserByUsername(username);
        String code1=(String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code)||!code.equalsIgnoreCase(code1)){
            return RespBean.error("验证码错误");
        }
        if (null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码错误");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用,请联系管理员");
        }

        String token=jwtTokenUtils.generateToken(userDetails);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokeHead);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken(userDetails,null,
               userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        return RespBean.success("登陆成功",map);
    }


    @Override
    public List<Admin> getalladmin(String keyword) {
       Integer id= ((Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        return adminMapper.getalladmin(id,keyword);
    }


    @Override
    public RespBean updateAdminPassword(String oldPass, String pass,Integer adminId) {
        Admin admin=adminMapper.selectById(adminId);
        BCryptPasswordEncoder encode =new BCryptPasswordEncoder();
        if (encode.matches(oldPass,admin.getPassword())){
            admin.setPassword(encode.encode(pass));
            if (1==adminMapper.updateById(admin)){
                return RespBean.success("更新密码成功");
            }
        }
        return RespBean.error("更新密码失败");
    }

    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin=adminMapper.selectById(id);
        admin.setUserFace(url);
        Integer result = adminMapper.updateById(admin);
        if (1==result){
            Admin admin1=(Admin)authentication.getPrincipal();
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin1,null,authentication.getAuthorities()));
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }
}
